package com.example.huawei.system.config.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.huawei.system.config.JwtAuthenticationToken;
import com.example.huawei.system.result.Result;
import com.example.huawei.system.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 从请求头中获取token
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7); // 去掉"Bearer "前缀
            try {
                Claims claims = JwtUtil.parseToken(token);
                if (claims.getExpiration().before(new Date())) { // 判断token是否过期
                    response.setStatus(200);
                    response.setContentType("application/json");
                    response.setCharacterEncoding("utf-8");
                    response.getWriter().print(JSONObject.toJSONString(Result.error().code(401).message("401登录信息失效")));
                    return;
                }
                // 生成Authentication对象，保存到SecurityContextHolder中
                Authentication authentication = new JwtAuthenticationToken(claims);
                SecurityContextHolder.getContext().setAuthentication(authentication);
            } catch (ExpiredJwtException e) {
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().print(JSONObject.toJSONString(Result.error().code(401).message("401登录信息失效")));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
